package com.lcxw.hxzbapi.controller.roomcontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.controller.giftandcubecontroller.GiftRealization;
import com.lcxw.hxzbapi.entity.pojo.Gift;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/room/line")
@CrossOrigin
@Slf4j
public class LineController {

    @Resource
    RoomRealization roomRealization;

    @Resource
    GiftRealization giftRealization;

    /**
     * 用户申请连麦
     */
    @PostMapping("/apply")
    public Response applyForLine(@RequestBody JSONObject requestBody) {

        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long userId = Long.parseLong(requestBody.getString("userId"));
        String roomType = requestBody.getString("roomType");
        JSONObject jsonObject = roomRealization.apply(roomId, roomType, userId);
        String status = jsonObject.getString("status");

        if ("full".equals(status)) {
            return Response.common(log, "申请连麦失败，连麦人数已满。", ErrorCode.INVALID_PARAM, "申请连麦失败，连麦人数已满。", null);
        } else if ("lining".equals(status)) {
            return Response.common(log, "申请连麦失败，已经在连麦中。", ErrorCode.NO_PERMISSION_SUPPLEMENT, "申请连麦失败，已经在连麦中。", null);
        } else if ("inPaipai".equals(status)) {
            return Response.common(log, "申请连麦失败，已经在拍拍中。", ErrorCode.NO_PERMISSION, "申请连麦失败，已经在拍拍中。", null);
        }
        roomRealization.applyLineChange(roomId);//申请连麦的人数变化，需要通知到前端
        return Response.ok(jsonObject.get("applyingUsers"));

    }

    /**
     * 用户取消连麦申请
     */
    @PostMapping("/apply/cancel")
    public Response cancelApply(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long userId = Long.parseLong(requestBody.getString("userId"));
        roomRealization.deleteApplyingUser(roomId, userId);
        roomRealization.applyLineChange(roomId);//申请连麦的人数变化，需要通知到前端
        return Response.ok();
    }

    /**
     * 主持人处理连麦申请
     */
    @PostMapping("/dealApply")
    public Response dealApply(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long applyUserId = Long.parseLong(requestBody.getString("applyUserId"));
        String decision = requestBody.getString("decision");

        if ("agree".equals(decision)) {
            roomRealization.deleteApplyingUser(roomId, applyUserId);
            roomRealization.addLineUser(roomId, applyUserId);
        } else if ("refuse".equals(decision)) {
            roomRealization.deleteApplyingUser(roomId, applyUserId);
        }
        roomRealization.applyLineChange(roomId);//申请连麦的人数变化，需要通知到前端
        return Response.ok();
    }

    /**
     * 获取房间当前申请连麦的所有用户id
     */
    @PostMapping("/applying/get")
    public Response getAllApplying(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        List applyingUsers = roomRealization.getApplyingUsers(roomId);
        return Response.ok(applyingUsers);
    }

    /**
     * 获取连麦中的用户id接口
     */
    @PostMapping("/lining/get")
    public Response getLining(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        List lineUsers = roomRealization.getLineUsers(roomId);
        return Response.ok(lineUsers);
    }

    /**
     * 连麦中的用户退出连麦
     */
    @PostMapping("/quitLining")
    public Response quitLining(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long userId = Long.parseLong(requestBody.getString("userId"));
        roomRealization.deleteLineUser(roomId, userId);
        return Response.ok();
    }

    /**
     * 主持人踢出一个连麦用户
     */
    @PostMapping("/lineUser/delete")
    public Response deleteOneLineUser(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long deleteUserId = Long.parseLong(requestBody.getString("deleteUserId"));
        roomRealization.deleteLineUser(roomId, deleteUserId);
        return Response.ok();
    }

    /**
     * 申请拍拍接口
     */
    @PostMapping("/paipai/apply")
    public Response applyPaipai(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long userId = Long.parseLong(requestBody.getString("userId"));
        String roomType = requestBody.getString("roomType");
        String isManager = requestBody.getString("isManager");

        //判断如果是主持人，则直接返回当前的申请拍拍的列表即可
        if ("1".equals(isManager)) {
            return Response.ok(roomRealization.getPaipaiApplyingUsers(roomId));
        }

        //判断房间类型，如果不是 video 或者 paipai 模式，则不允许申请拍拍
        if (!"video".equals(roomType) && !"paipai".equals(roomType)) {
            return Response.common(log, "该房间类型不能申请拍拍", 2001, "该房间类型不能申请拍拍", null);
        }
        JSONObject jsonObject;

        try {
            jsonObject = roomRealization.applyPaipai(roomType, roomId, userId);
        } catch (Exception e) {
            return Response.dbFail(log, "giftSend operate");
        }

        String status = jsonObject.getString("status");

        if ("noPermission".equals(status)) {
            return Response.common(log, "送礼不足，无权限申请拍拍", ErrorCode.NO_PERMISSION, "送礼不足，无权限申请拍拍", null);
        } else if ("full".equals(status)) {
            return Response.common(log, "当前拍拍位已满", ErrorCode.INVALID_PARAM, "当前拍拍位已满", null);
        } else if ("applying".equals(status)) {
            return Response.common(log, "已经在申请中队列中，不能重复申请", ErrorCode.NO_PERMISSION_SUPPLEMENT, "已经在申请中队列中，不能重复申请", null);
        }

        roomRealization.applyPaipaiChange(roomId);//申请拍拍的人数变化，需要通知到前端
        return Response.ok(jsonObject.get("paipaiApplyingUsers"));

    }

    /**
     * 用户取消申请拍拍
     */
    @PostMapping("/paipai/apply/cancel")
    public Response cancelApplyPaipai(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long userId = Long.parseLong(requestBody.getString("userId"));
        roomRealization.deletePaipaiApplyingUser(roomId, userId);
        roomRealization.applyPaipaiChange(roomId);//申请拍拍的人数变化，需要通知到前端
        return Response.ok();
    }

    /**
     * 主持人处理拍拍的申请
     */
    @PostMapping("/paipai/dealApply")
    public Response getPaipaiApplying(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long applyUserId = Long.parseLong(requestBody.getString("applyUserId"));
        String decision = requestBody.getString("decision");
        if ("agree".equals(decision)) {
            roomRealization.deletePaipaiApplyingUser(roomId, applyUserId);
            roomRealization.addPaipaiUser(roomId, applyUserId);
        } else if ("refuse".equals(decision)) {
            roomRealization.deletePaipaiApplyingUser(roomId, applyUserId);
        }
        roomRealization.applyPaipaiChange(roomId);//申请拍拍的人数变化，需要通知到前端
        return Response.ok();
    }

    /**
     * 获取当前正在拍拍上的用户id
     */
    @PostMapping("/paipaiUser/get")
    public Response getPaipaiUser(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        if (null == roomRealization.getPaipaiUsers(roomId)) {
            return Response.error(ErrorCode.INVALID_REQ, "当前拍拍位没有人");
        }
        String paipaiUsers = roomRealization.getPaipaiUsers(roomId);
        return Response.ok(paipaiUsers);
    }

    /*
     *踢出一个拍拍用户
     */
    @PostMapping("/paipaiUser/delete")
    public Response deletePaipaiUser(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long deleteUserId = Long.parseLong(requestBody.getString("deleteUserId"));
        roomRealization.deletePaipaiUser(roomId, deleteUserId);
        return Response.ok();
    }

    /*
     *设置拍拍，最低礼物要求设置
     */
    @PostMapping("/paipai/set")
    public Response setPaipaiGift(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        String roomType = requestBody.getString("roomType");
        int giftId = Integer.parseInt(requestBody.getString("giftId"));
        if (!"paipai".equals(roomType)) {
            return Response.error(ErrorCode.INVALID_REQ, "该房间类型不允许设置拍拍");
        }
        roomRealization.setPaipaiGift(roomId, giftId);
        return Response.ok();
    }

    /**
     * 获取允许拍拍的礼物列表
     */
    @PostMapping("/paipai/gift/get")
    public Response getPaipaiGift(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        List<Gift> paipaiGiftList = roomRealization.getPaipaiGifts(roomId);
        if (null == paipaiGiftList) {
            return Response.error(ErrorCode.INVALID_REQ, "房间还没有设置拍拍礼物");
        }
        Gift requirement = roomRealization.getPaipaiGift(roomId);
        JSONObject data = new JSONObject();
        data.put("requirement", requirement);
        data.put("paipaiGiftList", paipaiGiftList);
        return Response.ok(data);
    }

    /**
     * 拍拍礼物赠送
     */
    @PostMapping("/paipai/gift/send")
    public Response paipaiGiftSend(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("toUserId"));
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        long fromUserId = Long.parseLong(requestBody.getString("userId"));
        int giftId = Integer.parseInt(requestBody.getString("giftId"));
        int giftNum = Integer.parseInt(requestBody.getString("giftNum"));
        String  source =requestBody.getString("source");

        int  spendCoin ,result;
        JSONObject data = new JSONObject();

        try {
            //先将送礼记录存到数据库中
            result = giftRealization.sendGift(roomId, userId, fromUserId, giftId, giftNum,source);
            if (0 != result) {
                List<String> paipaiLine = roomRealization.getPaipaiLine(roomId);
                List<Integer> paipaiLineFire = new ArrayList<>();
                for (String lineUser:paipaiLine        ) {
                    int paipaiSend = roomRealization.getPaipaiSend(roomId, lineUser);
                    paipaiLineFire.add(paipaiSend);
                }
                data.put("needCoin",result);
                data.put("paipaiLine",paipaiLine);
                data.put("paipaiLineFire",paipaiLineFire);
                return Response.error(ErrorCode.INVALID_REQ, "金币不足", result);
            }
            //计算这次送礼花费了多少虚拟币
            spendCoin = giftRealization.spendCoin(giftId, giftNum);


        } catch (Exception e) {
            return Response.dbFail(log, "giftSend add");
        }

        roomRealization.setPaipaiSend(roomId,fromUserId,spendCoin);
        List<String> paipaiLine = roomRealization.getPaipaiLine(roomId);
        List<Integer> paipaiLineFire = new ArrayList<>();
        for (String lineUser:paipaiLine        ) {
            int paipaiSend = roomRealization.getPaipaiSend(roomId, lineUser);
            paipaiLineFire.add(paipaiSend);
        }
        data.put("needCoin",result);
        data.put("paipaiLine",paipaiLine);
        data.put("paipaiLineFire",paipaiLineFire);

        return Response.ok(data);
    }

    /**
     * 获取当前房间爆灯剩余时间接口
     */
    @PostMapping("/paipai/baodeng/countDown")
    public Response getBaodengCountDown(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        int baodengCountDown = roomRealization.getBaodengCountDown(roomId);
        if (-1 == baodengCountDown) {
            return Response.error(ErrorCode.INVALID_REQ, "该房间还没有爆灯");
        }
        return Response.ok(baodengCountDown);

    }

    /**
     * 获取拍拍房间中当前应该在连麦位的userId
     */
    @PostMapping("/paipai/lineUsers/get")
    public Response getPaipaiLineUsers(@RequestBody JSONObject requestBody) {
        long roomId = Long.parseLong(requestBody.getString("roomId"));
        JSONObject data = new JSONObject();
        List<String> paipaiLine = roomRealization.getPaipaiLine(roomId);
        List<Integer> paipaiLineFire = new ArrayList<>();
        for (String lineUser:paipaiLine        ) {
            int paipaiSend = roomRealization.getPaipaiSend(roomId, lineUser);
            paipaiLineFire.add(paipaiSend);
        }
        data.put("paipaiLine",paipaiLine);
        data.put("paipaiLineFire",paipaiLineFire);
        return Response.ok(data);
    }

}
